﻿using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ByteSite.Common;
using System.Linq.Expressions;
using ByteSite.Quartz;
using Quartz;
using Quartz.Impl.Matchers;
using System.Threading.Tasks;
using System.Linq;

namespace ByteSite.Web.admin.manager
{
    public partial class task_list : Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string keywords = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.keywords = DTRequest.GetQueryString("keywords");

            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("task_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                Entitys.dt_manager model = GetAdminInfo(); //取得当前管理员信息
                RptBind(CombSqlTxt(keywords), x => x.id);
            }
        }

        protected string GetNextFireTime(string id)
        {
            Task<IScheduler> sch = QuartzHelper.GetScheduler();
            IScheduler isch = sch.Result;
            Task<IReadOnlyCollection<string>> _groups = isch.GetJobGroupNames();
            IReadOnlyCollection<string> groups = _groups.Result;
            if (groups.Count == 0)
                return "";
            string groupName = groups.First(x => x == "default");
            if (string.IsNullOrEmpty(groupName))
                return "";
            Task<IReadOnlyCollection<JobKey>> _jobKeys = isch.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName));
            if (_jobKeys.Result.Count == 0)
                return "";
            if (!_jobKeys.Result.Any(x => x.Name == id && x.Group == "default"))
                return "";
            JobKey jobKey = _jobKeys.Result.First(x => x.Name == id && x.Group == "default");
            string jobName = jobKey.Name;
            string jobGroup = jobKey.Group;
            Task<IReadOnlyCollection<ITrigger>> _triggers = isch.GetTriggersOfJob(jobKey);
            ITrigger trigger = _triggers.Result.ToList()[0];
            DateTimeOffset? dto = trigger.GetNextFireTimeUtc();
            DateTime dt = Convert.ToDateTime(dto.ToString());
            DateTime nextJobTime = TimeZone.CurrentTimeZone.ToLocalTime(dt);
            return nextJobTime.ToString("yyyy/MM/dd HH:mm:ss");

        }

        protected string GetType(string type)
        {
            if (type == "dll")
                return "热加载";
            else if (type == "url")
                return "Url";
            else if (type == "email")
                return "邮件";
            else if (type == "mqtt")
                return "MQTT";
            else if (type == "rabbitmq")
                return "RabbitMQ";
            else
                return "未知类型";
        }
        protected string GetStatus(string status)
        {
            if (status == "0")
                return "等待";
            else if (status == "1")
                return "暂停";
            else if (status == "2")
                return "正常";
            else if (status == "3")
                return "阻塞";
            else if (status == "4")
                return "错误";
            else
                return "未知";
        }

        #region 数据绑定=================================
        private void RptBind(Expression<Func<Entitys.QuartzTask, bool>> whereExpression, Expression<Func<Entitys.QuartzTask, object>> orderExpression)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            txtKeywords.Text = this.keywords;
            BLL.quartz_task bll = new BLL.quartz_task();
            this.rptList.DataSource = bll.GetList(this.pageSize, this.page, whereExpression, orderExpression, out this.totalCount);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("task_list.aspx", "keywords={0}&page={1}", this.keywords, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected Expression<Func<Entitys.QuartzTask, bool>> CombSqlTxt(string _keywords)
        {
            Expression<Func<Entitys.QuartzTask, bool>> expression = t => true;
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                expression = expression.And(x => x.name.Contains(_keywords) || x.intro.Contains(_keywords));
            }
            return expression;
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("manager_page_size", "ByteSitePage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("task_list.aspx", "keywords={0}", txtKeywords.Text));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("manager_page_size", "ByteSitePage", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("task_list.aspx", "keywords={0}", this.keywords));
        }
        protected void btnStart_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("task_list", DTEnums.ActionEnum.Confirm.ToString()); //检查权限
            BLL.quartz_task bll = new BLL.quartz_task();
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    Entitys.QuartzTask model = bll.GetModel(id);
                    QuartzHelper.StartJob(model.id.ToString(), model.group).GetAwaiter();
                }
            }
            JscriptMsg("执行完成","");

        }
        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("task_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            BLL.quartz_task bll = new BLL.quartz_task();
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {

                    Entitys.QuartzTask model = bll.GetModel(id);
                    QuartzHelper.DeleteJob(model.id.ToString(), model.group).GetAwaiter();

                    if (bll.Delete(id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("task_list.aspx", "keywords={0}", this.keywords));
        }

    }
}